﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GUI.UserInterfaces
{
    public partial class GUIUpdate : Form
    {
        public GUIUpdate()
        {
            InitializeComponent();

            downloadFile(UTIL.KZSettings.XMLFiles);
        }

        private Queue<string> _downloadUrls = new Queue<string>();


        private void downloadFile(IEnumerable<string> urls)
        {
            foreach (var file in urls)
            {
                _downloadUrls.Enqueue(UTIL.KZSettings.XMLURL(file));
            }

            ucDownload.progressBar1.Visible = true;
            ucDownload.lblFileName.Visible = true;

            DownloadFile();
        }

        private void DownloadFile()
        {
            if (_downloadUrls.Any())
            {
                WebClient client = new WebClient();

                client.DownloadProgressChanged += client_DownloadProgressChanged;
                client.DownloadFileCompleted += client_DownloadFileCompleted;

                var url = _downloadUrls.Dequeue();

                string FileName = url.Substring(url.LastIndexOf("/") + 1, (url.Length - url.LastIndexOf("/") - 1)) + ".xml";

                //if (!File.Exists(FileName))
                //{
                //    File.Create(FileName);
                //}

                client.DownloadFileAsync(new Uri(url), FileName);
                ucDownload.lblFileName.Text = FileName.Split(new Char[] { '.' })[0];

                return;
            }

            this.Visible = false;

            GUIMain main = GUIMain.Instance;
            main.ShowDialog();

            this.Close();
        }

        private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            DownloadFile();
        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            double bytesIn = double.Parse(e.BytesReceived.ToString());
            double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
            double percentage = bytesIn / totalBytes * 100;

            ucDownload.progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
        }
    }
}
